import {checkTokenAPI} from "@/api/sys/login"

const saveUserToken = (resp) => {
    //即保存令牌
    localStorage.setItem("token", resp.token);

    //还保存用户信息
    localStorage.setItem("userInfo",JSON.stringify(resp.user));
}

const getUserToken = () => {
    let token = localStorage.getItem("token")
    if(token == null || token == undefined || token === ""){
        return "";
    }

    return token;
}


/**
 * {
 *    "id": 1,
 *    "loginName": "admin",
 *    "loginPwd": "E10ADC3949BA59ABBE56E057F20F883E",
 *    "headerImg": "2.png",
 *    "lastLogin": "2023-09-18 12:42:09",
 *    "accountStatus": 1,
 *    "safeEmail": "admin@admin.com",
 *    "createTime": "2023-09-01 12:42:01"
 *  }
 * @returns {any}
 */
const getUserInfo = ()=>{
    let str = localStorage.getItem("userInfo");
    return JSON.parse(str);
}

const  updateUserInfo = (info)=>{
    //还保存用户信息
    localStorage.setItem("userInfo",JSON.stringify(info));
}

//检查令牌合法性
const isAuthentication = async () => {
    //拿到之前登录存到里面的令牌
    // 给后端发送请求，检查令牌是否合法
    let resp = await checkTokenAPI();
    console.log("检查令牌：",resp)

    if (resp.data.code === 200) {
        return true;
    }
    return false;

}

export {saveUserToken, getUserToken, isAuthentication,getUserInfo,updateUserInfo}
